<template>
  <!-- 搜索表单 -->
  <item-search @search="reload"/>
  <!--:parse-data="parseData"-->
  <div>
    <ele-pro-table
      ref="tableRef"
      :columns="columns"
      :datasource="datasource"
      :pagination="false"
      :show-overflow-tooltip="true"
      v-model:selections="selections"
      highlight-current-row
      cache-key="cmsItemTable"
      :where="defaultWhere"
      row-key="id"
      :load-on-created="false"
    >
      <template #toolbar>
        <el-button
          type="primary"
          class="ele-btn-icon"
          :icon="PlusOutlined"
          @click="openAdd()"
        >
          新建
        </el-button>
      </template>
      <template #action="{ row }">
        <el-link type="primary" :underline="false" @click="openEdit(row)">
          修改
        </el-link>
        <el-divider direction="vertical"/>
        <el-link type="danger" :underline="false" @click="removeBatch(row)">
          删除
        </el-link>
      </template>
      <template #imageUrl="{row}">
        <el-image v-if="row.imageUrl" style="width: 32px;height: 32px; border-radius: 50%; vertical-align: -16px"
                  :src="row.imageUrl"
                  lazy :preview-src-list="[row.imageUrl]" :preview-teleported="true">
          <div slot="error" class="image-slot">
            <i class="el-icon-collection"></i>
          </div>
        </el-image>
        <el-avatar v-if="!row.imageUrl" src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                   :size="32" @click.stop=""
                   style="vertical-align: -16px">
        </el-avatar>
      </template>
      <template #status="{ row }">
        <el-switch
          :model-value="row.status == 0"
          @change="(checked) => editStatus(checked, row)"
        />
      </template>
    </ele-pro-table>
  </div>

  <!-- 新增弹窗 -->
  <item-add v-if="showAdd" v-model="showAdd" :typeId="props.typeId" @done="reload"></item-add>
  <!-- 编辑弹窗 -->
  <item-edit v-model="showEdit" :typeId="props.typeId" :data="current" @done="reload"/>
</template>

<script setup>
import {ref, reactive, watch} from 'vue';
import {
  PlusOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@/components/icons';
import {ElMessageBox} from 'element-plus/es';
import {EleMessage} from 'ele-admin-plus/es';
import ItemSearch from './nav-item-search.vue';
import ItemAdd from './nav-item-add.vue';
import ItemEdit from './nav-item-edit.vue';
import {pageItems, removeItems, updateItemsStatus} from '@/api/cms/nav/item';
import {handleTree} from '@/utils/linyang';


const props = defineProps({
  typeId: Number
});

/** 默认搜索条件 */
const defaultWhere = reactive({
  typeId: props.typeId
});

/** 表格实例 */
const tableRef = ref(null);

/** 表格列配置 */
const columns = ref([
  {
    prop: 'name',
    label: '名称',
    align: 'left',
    minWidth: 150
  },
  {
    prop: 'orderNum',
    label: '显示顺序',
    align: 'center',
    minWidth: 80
  },
  {
    prop: 'imageUrl',
    label: '图标',
    align: 'center',
    minWidth: 90,
    slot: 'imageUrl',
  },
  {
    prop: 'redirectUrl',
    label: '跳转链接',
    align: 'left',
    minWidth: 200
  },
  {
    prop: 'status',
    label: '状态',
    align: 'center',
    minWidth: 90,
    slot: 'status',
  },
  {
    columnKey: 'action',
    label: '操作',
    width: 180,
    align: 'center',
    slot: 'action'
  }
]);

/** 表格选中数据 */
const selections = ref([]);

/** 当前编辑数据 */
const current = ref(null);

/** 是否显示编辑弹窗 */
const showAdd = ref(false);

/** 是否显示编辑弹窗 */
const showEdit = ref(false);

/** 表格数据源 */
const datasource = async ({pages, where}) => {
  const result = await pageItems({...where, ...pages});
  // console.log('result:', result);
  return handleTree(result.data, "id", "parentId");
};

/** 搜索 */
const reload = (where) => {
  tableRef.value?.reload?.({page: 1, where});
};

/** 打开新增弹窗 */
const openAdd = () => {
  //判断当前是否已经选定链接的类别，如果没有选择，先提示用户选择
  if (!props.typeId) {
    EleMessage.warning("请先在左侧选择一个所属链接类别");
    return;
  }
  showAdd.value = true;
};

/** 打开编辑弹窗 */
const openEdit = (row) => {
  if (!props.typeId) {
    EleMessage.warning("请先在左侧选择一个所属链接类别");
    return;
  }
  current.value = row ?? null;
  showEdit.value = true;
};

/** 批量删除 */
const removeBatch = (row) => {
  const rows = row == null ? selections.value : [row];
  if (!rows.length) {
    EleMessage.error('请至少选择一条数据');
    return;
  }
  ElMessageBox.confirm(
    `是否确认删除项目名称为"${rows.map((d) => d.name).join()}"的数据项?`,
    '系统提示',
    {type: 'warning', draggable: true}
  )
    .then(() => {
      const loading = EleMessage.loading('请求中..');
      removeItems(rows.map((d) => d.id))
        .then(() => {
          loading.close();
          EleMessage.success('删除成功');
          reload();
        })
        .catch((e) => {
          loading.close();
          EleMessage.error(e.message);
        });
    })
    .catch(() => {
    });
};


// editStatus

/** 修改链接状态 */
const editStatus = (checked, row) => {
  const status = checked ? '0' : '1';
  updateItemsStatus(row.id, status)
    .then((msg) => {
      row.status = status;
      EleMessage.success(msg);
    })
    .catch((e) => {
      EleMessage.error(e.message);
    });
};

watch(
  () => props.typeId,
  (typeId) => {
    if (typeId) {
      defaultWhere.typeId = props.typeId;
      tableRef.value?.reload?.();//刷新当前表格
    }
  }
);


</script>
